package org.windblog.core;

import java.text.DateFormat;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.Arrays;
import java.util.Calendar;
import java.util.Enumeration;
import java.util.GregorianCalendar;
import java.util.HashMap;
import java.util.LinkedList;
import java.util.List;
import javax.servlet.ServletContext;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.windblog.api.template.TemplateService;
import org.windblog.core.entity.Category;
import org.windblog.core.entity.File;
import org.windblog.core.entity.Page;
import org.windblog.core.entity.Post;

public class WBQuery {
	
	private static String query;	//请求参数字符串

	private static HashMap<String, String> queryVars;	//参数列表

	private static List<Post> posts;	//结果posts

	private static Post currentPost;	//一条结果的请求

	private static Page currentPage;    //当前page 

	private static int postCount;		//Post数目
	
	private static Date time;			//archive发布的时间
	
	private static String title;        //category Title
	
	private static boolean isSingle;	//是否请求的post

	private static boolean isPage;		//是否请求的page

	private static boolean isArchive;	//是否请求的Archive

	private static boolean isCategory;	//是否请求的Category(分类)

	private static boolean isTag;		//是否请求的Tag(标签)

	private static boolean isHome;		//是否请求的主页

	private static boolean isMonth;		//是否请求的按月归档

	private static boolean is404;		//发生没有找到错误

	private static boolean isYear;		//是否请求的按年归档
	
	private static boolean isSearch;	//是否是请求的搜索
	
	private static boolean isAttachment; //是否请求的文件
	
	private static HttpServletRequest request;
	
	private static HttpServletResponse response;
	
	private static ServletContext servletContext;
	
	public static void setRequest(HttpServletRequest request) {
		WBQuery.request = request;
	}

	public static void setResponse(HttpServletResponse response) {
		WBQuery.response = response;
	}

	public static void setServletContext(ServletContext servletContext) {
		WBQuery.servletContext = servletContext;
	}

	public static ServletContext getServletContext() {
		return servletContext;
	}

	public static HttpServletRequest getRequest() {
		return request;
	}

	public static HttpServletResponse getResponse() {
		return response;
	}

	public static Page getCurrentPage() {
		return currentPage;
	}
	
	public static boolean isAttachment()
	{
		return isAttachment;
	}
	public static boolean isSearch()
	{
		return isSearch;
	}
	
	public static String getTitle()
	{
		return title;
	}
	
	public static String getTime(String format)
	{
		DateFormat df = new SimpleDateFormat(format);
		return df.format(time);
	}
	
	public static boolean isYear()
	{
		return isYear;
	}
	
	public static boolean isSingle() {
		return isSingle;
	}

	public static boolean isPage() {
		return isPage;
	}

	public static boolean isArchive() {
		return isArchive;
	}

	public static boolean isCategory() {
		return isCategory;
	}

	public static boolean isTag() {
		return isTag;
	}

	public static boolean isHome() {
		return isHome;
	}

	public static boolean isMonth() {
		return isMonth;
	}

	public static boolean is404() {
		return is404;
	}

	public static int getPostCount() {
		return postCount;
	}

	public static void setPostCount(int postcount) {
		postCount = postcount;
	}

	public static Post getCurrentPost() {
		return currentPost;
	}

	public static void setCurrentPost(Post currentpost) {
		currentPost = currentpost;
	}

	public static String getQuery() {
		return query;
	}

	public static void setQuery(String _query) {
		query = _query;
	}

	public static HashMap<String, String> getQueryVars() {
		return queryVars;
	}

	public static void setQueryVars(HashMap<String, String> _queryVars) {
		queryVars = _queryVars;
	}

	public static List<Post> getPosts() {
		return posts;
	}

	public static void setPosts(List<Post> _posts) {
		posts = _posts;
	}

	// methods

	public static void init()
	{
		query        = null;
		queryVars    = new HashMap<String, String>();
		posts        = new LinkedList<Post>();
		time         = new Date();
		title        = "";
		isSingle     = false;
		isPage       = false;
		is404        = false;
		isArchive    = false;
		isCategory   = false;
		isHome       = false;
		isSingle     = false;
		isTag        = false;
		isMonth      = false;
		isYear       = false;
		isSearch     = false;
		isAttachment = false;
	}
	
	@SuppressWarnings("unchecked")
	public static void parseQuery() {
		/**
		 *  
		 *  处理请求，参数有如下几个:
		 *  p : post的字符串形式的key.
		 *  page_id : page的Stringkey.
		 *  cat : category的stringkey.
		 *  m : 按月的Archive.("m=201010"表示ʾ2010年10月的Archive m=20109表示2010年9月)
		 *  y : 按年的Archive.("y=2010"表示ʾ2010年的Archive)
		 *  s : 搜索的关键字.("s=abc" 表示搜索abc相关的内容)
		 *  f : 文件strkey
		 */
		String[] params = { "p", "cat", "page_id", "m" ,"s","f"};

		List<String> expectParams = new LinkedList<String>(
				Arrays.asList(params));
		
		TemplateService.init();
		
		Enumeration<String> paramNames = request.getParameterNames();
		while (paramNames.hasMoreElements()) {
			String curParamName = paramNames.nextElement();
			if (expectParams.contains(curParamName)) {
				queryVars.put(curParamName, request.getParameter(curParamName));
			}
		}

		// �������Ϊ����Ĭ��Ϊ������ҳ
		if (queryVars.isEmpty()) {
			isHome = true;
			posts = PostService.getPosts("");
			postCount = posts.size();
			if(postCount>0)
				currentPost = posts.get(0);
			return;
		}

		// if it is post.
		if (queryVars.get("p") != null) {
			isSingle = true;
			currentPost = PostService.getPost(queryVars.get("p"));
			if(currentPost!=null)
				postCount=1;
			else
				postCount=0;
			return;
		}

		// if it is cat
		if (queryVars.get("cat") != null) {
			isCategory = true;
			Category c = CategoryService.getCategory(queryVars.get("cat"));
			posts = c.getPosts();
			title = c.getName();
		}

		// if it is page
		if (queryVars.get("page_id") != null) {
			isPage = true;
			currentPage = PageService.getPage(queryVars.get("page_id"));
			return ;
			
		}

		// if it is Month
		if (queryVars.get("m") != null) {
			isMonth = true;
			int year = Integer.parseInt(queryVars.get("m").substring(0, 4));
			int month = Integer.parseInt(queryVars.get("m").substring(4))-1;
			Calendar cmin = GregorianCalendar.getInstance();
			cmin.set(year, month, 1);
			time = cmin.getTime();
			Calendar cmax = GregorianCalendar.getInstance();
			cmax.set(year, month+1, 1);
			List<Post> tposts = PostService.getPosts("");
			posts = new LinkedList<Post>();
			for(Post p : tposts)
			{
				if(!p.getDate().before(cmin.getTime()) && p.getDate().before(cmax.getTime()))
				{
					posts.add(p);
				}
			}
			postCount = posts.size();
			if(postCount>0)
				currentPost = posts.get(0);
			return;
		}
		
		// if it is file
		if (queryVars.get("f") != null) {
			isAttachment = true;
			isSingle = true;
			currentPost = new Post();
			postCount=1;
			File file = FileService.getFile(queryVars.get("f"));
			currentPost.setTitle("<a href=\""+file.getDownloadLink()+"\">"+file.getTitle()+"</a>");
			currentPost.setContent(file.getDescription());
			currentPost.setCommentStatus("NO_COMMENTS");
			currentPost.setDate(file.getDate());
			currentPost.setAuthor(file.getAuthor());
			return;
		}
		
	}
}
